package com.ssyc.student.activity;

import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.MediaPlayerManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.vp.SuperViewPager;
import com.ssyc.student.R;
import com.ssyc.student.bean.TextPrepareInfo;
import com.ssyc.student.fragment.StudentTextChooseAnswerFragment;
import com.ssyc.student.fragment.StudentTextCommitFragment;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--金牌金概念2--题型选择--课文预习界面
 * Created by Administrator on 2018/5/14 0014.
 */

public class StudentTextPrepareActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //课程的LessonId在提交界面可能需要该值,页面传递过来
    private String lessonId;

    //gradeId
    private String gradeId;

    //加载框
    private RelativeLayout rlLoading;


    //内容布局
    private LinearLayout llContent;

    //返回按钮
    private ImageView ivBack;

    //顶部的文本内容
    private TextView tvTopContent;

    //顶部的播放按钮
    private ImageView ivPlay;

    //底部的ViewPager
    private SuperViewPager vp;

    //底部的显示Vp页数的文本
    private TextView tvPos;


    //句子段落的音频文件Url
    private String voiceUrl;


    //填充ViewPager的Fragment集合
    private List<Fragment> mFragments;


    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //记录当前ViewPager滑动的位置
    private int pos = 0;


    //听力稿
    private String example;

    //是否为查看答案
    private String isCheck;


    //Handler对象
    private Handler handler = new Handler();

    //用于保存做题的选择题目答案的Map,key为当前的位置,value为选择的答案
    public static Map<Integer, String> chooseAnswerMap;

    //用于保存用户答题的对错的Map,key为当前的位置,value为答题的状态值
    public static Map<Integer, Boolean> answerMap;

    //用于上传服务器记录时间的id
    private String rowId;
    private String energy;


    //记录用户保存的时间
    public static long firstTime;

    //播放段落音频文件的帧动画对象
    private AnimationDrawable animationDrawable;

    //静态代码块
    {
        //这里使用有序的Map来存放题目
        chooseAnswerMap = new LinkedHashMap<>();
        answerMap = new LinkedHashMap<>();

        //记录用户第一次进入的时间
        firstTime = System.currentTimeMillis();

        //初始化记录的时间
        TimeCount.init();
    }

    //获取保存答题Map的方法
    public static Map<Integer, String> getChooseAnswerMap() {
        return chooseAnswerMap;
    }

    //获取保存答题正确或者错误Map的方法
    public static Map<Integer, Boolean> getAnswerMap() {
        return answerMap;
    }

    /**
     * 提供获取第一次进入时间的方法
     *
     * @return
     */
    public static long getFirstTime() {
        return firstTime;
    }


    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_text_prepare;
    }

    @Override
    protected void init() {

        showContent();

        //初始化View
        initView();

        //获取传递过来的Intent对象
        initIntent();

        //请求服务器获取页面数据
        http();

    }


    /**
     * 初始化控件
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvTopContent = findViewById(R.id.tv__text_content);
        ivPlay = findViewById(R.id.iv_play);
        ivPlay.setOnClickListener(this);
        vp = findViewById(R.id.vp);
        tvPos = findViewById(R.id.tv_vp_pos);
        vp.addOnPageChangeListener(this);
        rlLoading = findViewById(R.id.rl_loading_view);
        rlLoading.setVisibility(View.VISIBLE);
        llContent = findViewById(R.id.ll_content);
        llContent.setVisibility(View.GONE);
    }

    /**
     * 获取传递的数据
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);
    }

    /**
     * 网络请求获取页面数据的方法
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "20");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lesson", "Lesson" + lessonId);
        map.put("examtype", "11");
        map.put("role", AccountUtils.getRole(this));


        LogUtils.iTag("test", "接口是:" + HttpAdress.TEXTPREPARE + "");

        HttpUtils.post(HttpAdress.TEXTPREPARE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    if (null != rlLoading) {
                        rlLoading.setVisibility(View.GONE);
                    }
                    if (null != llContent) {
                        llContent.setVisibility(View.VISIBLE);
                    }
                    TextPrepareInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, TextPrepareInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            TextPrepareInfo.DataBean data = info.getData();
                            if (null != data) {

                                //设置题目的内容
                                setTopContent("Lesson preparation");

                                //获取音频文件Url地址
                                voiceUrl = data.getSound();

                                LogUtils.iTag("test", "音频地址是:" + voiceUrl);

                                //获取听力稿
                                example = data.getExample();

                                //取出所有问题的集合
                                List<TextPrepareInfo.DataBean.QuestionListBean> question_list = data.getQuestion_list();


                                if (null != question_list && question_list.size() != 0) {

                                    //初始化填充的Framgent
                                    initFragments(question_list);

                                    //设置Vp
                                    initVp();
                                }
                            }

                        } else {
                            //服务器返回异常状态码
                            UiUtils.Toast("服务器异常", false);
                            Log.i("test", "返回异常码是:" + info.getState());
                        }
                    }
                }
            }
        });
    }

    /**
     * 设置大标题的方法
     *
     * @param bigtitle
     */
    private void setTopContent(String bigtitle) {
        if (!TextUtils.isEmpty(bigtitle)) {
            tvTopContent.setText(bigtitle);
        }
    }


    /**
     * 初始化Fragments的方法,需要在请求服务器后获取到数据后执行
     */
    private void initFragments(List<TextPrepareInfo.DataBean.QuestionListBean> question_list) {
        mFragments = new ArrayList<>();

        for (int i = 0; i < question_list.size(); i++) {
            mFragments.add(StudentTextChooseAnswerFragment.newInstance(question_list.get(i), i, example));
            chooseAnswerMap.put(i, "");
            answerMap.put(i, false);
        }

        //添加最后一个提交页面的Fragment
        mFragments.add(StudentTextCommitFragment.newInstance(GsonUtil.listToJson(question_list), lessonId, gradeId));

        //设置当前展示的Vp的页码
        tvPos.setText("1/" + (mFragments.size() - 1));
    }


    /**
     * 设置ViewPager的方法
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * ViewPager的滚动监听
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pos = position;
        if (position != mFragments.size() - 1) {
            tvPos.setVisibility(View.VISIBLE);
            tvPos.setText((position + 1) + "/" + (mFragments.size() - 1));
        } else {
            tvPos.setVisibility(View.GONE);
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 接受事件的方法
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        //通知ViewPager翻页
        if (null != busInfo && StudentTextChooseAnswerFragment.VPSCOLL.equals(busInfo.vpScoll)) {
            pos += 1;
            //延迟800毫秒跳转页面
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    vp.setCurrentItem(pos);
                }
            }, 300);
        } else if (null != busInfo && StudentShowTextAnswerActivity.LOOKANSWER == busInfo.getType()) {
            //查看答案的标识
            vp.setCurrentItem(0);

            isCheck = "y";

        }
    }

    /**
     * 做播放动画的操作方法
     */
    private void doPlayVoiceAnim() {
        if (!TextUtils.isEmpty(voiceUrl)) {

            if (null != animationDrawable && animationDrawable.isRunning()) {
                animationDrawable.stop();
                animationDrawable = null;
                ivPlay.setImageResource(R.drawable.st_voice_big_anim);
            }

            //进行帧动画操作
            animationDrawable = (AnimationDrawable) ivPlay.getDrawable();
            animationDrawable.start();
            //播放音频
            MediaPlayerManager.getInstance().playbar(voiceUrl, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    if (null != animationDrawable) {
                        animationDrawable.stop();
                        ivPlay.setImageResource(R.drawable.st_voice_big_anim);
                    }
                }
            }, new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    if (null != animationDrawable) {
                        animationDrawable.stop();
                        ivPlay.setImageResource(R.drawable.st_voice_big_anim);
                    }
                    return false;
                }
            });

        }
    }

    /**
     * 页面控件的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //关闭
            finish();
        } else if (id == R.id.iv_play) {
            UIHelper.dismissDialog();
            //防止连点
            if (UiUtils.isNotFasterClick()) {

                UIHelper.showDialog(this, "音频加载中...");

                //做播放动画的处理
                doPlayVoiceAnim();

            }
        }
    }


    /**
     * 该生命周期内请求服务器记录初次进入的时间
     */
    @Override
    protected void onResume() {
        super.onResume();


        if (TextUtils.isEmpty(isCheck)) {
            Log.i("test", "onResume");
            RecordTimeUtil.httpEnterTime(this, lessonId, gradeId, "11",
                    new RecordTimeUtil.onRecordRowIdListener() {
                        @Override
                        public void recordRowId(String id, String en) {

                            rowId = id;
                            energy = en;
                        }
                    });
        }
    }

    /**
     * 考虑熄屏
     */
    @Override
    protected void onPause() {
        super.onPause();

        long time = System.currentTimeMillis() - TimeCount.newInstance().getLastTime();

        //计算总用时
        long totalTime = TimeCount.newInstance().getTotalTime() + time;

        //记录总用时
        TimeCount.newInstance().setTotalTime(totalTime);


        if (TextUtils.isEmpty(isCheck)) {
            Log.i("test", "onPause");
            //上传服务器记录时间的接口
            RecordTimeUtil.httpExitTime(rowId, this);
        }
    }

    /**
     * 考虑亮屏
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        //重置LastTime
        TimeCount.newInstance().setLastTime(System.currentTimeMillis());
    }

    /**
     * 生命周期中释放对象,防止内存泄漏
     */
    @Override
    protected void onDestroy() {
        if (null != animationDrawable) {
            animationDrawable.stop();
            ivPlay.setImageResource(R.drawable.st_voice_big_anim);
        }
        MediaPlayerManager.getInstance().stop();
        super.onDestroy();
    }
}
